﻿using Apache.NMS;
using Apache.NMS.ActiveMQ;
using Apache.NMS.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CsharpWpfManual
{
    /// <summary>
    /// ActiveMQ.xaml 的交互逻辑
    /// </summary>
    public partial class ActiveMQ : Window
    {
        public ActiveMQ()
        {
            InitializeComponent();
            Testactivemq = new CTestactivemq();
            CTestactivemq.ReveieveMsgEvent += (t) => { Dispatcher.Invoke(() => { recvmsgtxt.Text = t; }); };
        }
        CTestactivemq Testactivemq;

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            //CTestactivemq.ReveieveMsgEvent = null;
            Testactivemq.Dispose();
        }



        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Testactivemq.ProducerCreateMessage(txtsendmsg.Text);
        }
    }

    public class CTestactivemq :IDisposable
    {
        protected static AutoResetEvent semaphore = new AutoResetEvent(false);
        protected static ITextMessage message = null;
        protected static TimeSpan receiveTimeout = TimeSpan.FromSeconds(10);
        public static event Action<string> ReveieveMsgEvent; 

        Uri connecturi = new Uri("tcp://localhost:61616/");

        IMessageProducer producer = null;
        IMessageConsumer consumer = null;
        IConnection connection = null;
        ISession session = null;
        public  CTestactivemq()
        {
            // 创建生产者
            IConnectionFactory factory = new NMSConnectionFactory(connecturi);

            connection = factory.CreateConnection();
            session = connection.CreateSession();
            {

                IDestination destination = SessionUtil.GetDestination(session, "queue://FOO.BAR");

                Console.WriteLine("Using destination: " + destination);

                // Create a   producer
                producer = session.CreateProducer(destination);
                {
                    // Start the connection so that messages will be processed.
                    connection.Start();
                    producer.DeliveryMode = MsgDeliveryMode.Persistent;
                    producer.RequestTimeout = receiveTimeout;


                }

                consumer = session.CreateConsumer(destination);
                {
                    consumer.Listener += new MessageListener(OnMessage);
                }
            }
        }



        public void ProducerCreateMessage(string msg)
        {

            // Send a message
            ITextMessage request = session.CreateTextMessage(msg);
            request.NMSCorrelationID = "abc";
            request.Properties["NMSXGroupID"] = "cheese";
            request.Properties["myHeader"] = "Cheddar";

            producer.Send(request);

        }

        public void ProducerCreateMessage(byte[] msg)
        {

            // Send a message
            IBytesMessage request = session.CreateBytesMessage(msg);
            request.NMSCorrelationID = "abc";
            request.Properties["NMSXGroupID"] = "cheese";
            request.Properties["myHeader"] = "Cheddar";

            producer.Send(request);

        }
        public void ProducerCreateMessage(object msg)
        {

            // Send a message
            IObjectMessage request = session.CreateObjectMessage(msg);
            request.NMSCorrelationID = "abc";
            request.Properties["NMSXGroupID"] = "cheese";
            request.Properties["myHeader"] = "Cheddar";

            producer.Send(request);

        }
        public void ProducerCreateMessage()
        {

            // Send a message
            IMapMessage request = session.CreateMapMessage();
            request.NMSCorrelationID = "abc";
            request.Properties["NMSXGroupID"] = "cheese";
            request.Properties["myHeader"] = "Cheddar";

            producer.Send(request);

        }


        public static void Testactivemq()
        {
            // Example connection strings:
            //    activemq:tcp://activemqhost:61616
            //    stomp:tcp://activemqhost:61613
            //    ems:tcp://tibcohost:7222
            //    msmq://localhost

            Uri connecturi = new Uri("activemq:tcp://activemqhost:61616");

            Console.WriteLine("About to connect to " + connecturi);

            // NOTE: ensure the nmsprovider-activemq.config file exists in the executable folder.
            IConnectionFactory factory = new NMSConnectionFactory(connecturi);

            using (IConnection connection = factory.CreateConnection())
            using (ISession session = connection.CreateSession())
            {
                // Examples for getting a destination:
                //
                // Hard coded destinations:
                //    IDestination destination = session.GetQueue("FOO.BAR");
                //    Debug.Assert(destination is IQueue);
                //    IDestination destination = session.GetTopic("FOO.BAR");
                //    Debug.Assert(destination is ITopic);
                //
                // Embedded destination type in the name:
                //    IDestination destination = SessionUtil.GetDestination(session, "queue://FOO.BAR");
                //    Debug.Assert(destination is IQueue);
                //    IDestination destination = SessionUtil.GetDestination(session, "topic://FOO.BAR");
                //    Debug.Assert(destination is ITopic);
                //
                // Defaults to queue if type is not specified:
                //    IDestination destination = SessionUtil.GetDestination(session, "FOO.BAR");
                //    Debug.Assert(destination is IQueue);
                //
                // .NET 3.5 Supports Extension methods for a simplified syntax:
                //    IDestination destination = session.GetDestination("queue://FOO.BAR");
                //    Debug.Assert(destination is IQueue);
                //    IDestination destination = session.GetDestination("topic://FOO.BAR");
                //    Debug.Assert(destination is ITopic);
                IDestination destination = SessionUtil.GetDestination(session, "queue://FOO.BAR");

                Console.WriteLine("Using destination: " + destination);

                // Create a consumer and producer
                using (IMessageConsumer consumer = session.CreateConsumer(destination))
                using (IMessageProducer producer = session.CreateProducer(destination))
                {
                    // Start the connection so that messages will be processed.
                    connection.Start();
                    producer.DeliveryMode = MsgDeliveryMode.Persistent;
                    producer.RequestTimeout = receiveTimeout;

                    consumer.Listener += new MessageListener(OnMessage);

                    // Send a message
                    ITextMessage request = session.CreateTextMessage("Hello World!");
                    request.NMSCorrelationID = "abc";
                    request.Properties["NMSXGroupID"] = "cheese";
                    request.Properties["myHeader"] = "Cheddar";

                    producer.Send(request);

                    // Wait for the message
                    semaphore.WaitOne((int) receiveTimeout.TotalMilliseconds, true);

                    if(message == null)
                    {
                        Console.WriteLine("No message received!");
                    }
                    else
                    {
                        Console.WriteLine("Received message with ID:   " + message.NMSMessageId);
                        Console.WriteLine("Received message with text: " + message.Text);
                    }
                }
        }
    }

    protected static void OnMessage(IMessage receivedMsg)
    {
        message = receivedMsg as ITextMessage;
            ReveieveMsgEvent?.Invoke(message.Text);
    }

        public void Dispose()
        {
            producer.Dispose();
            consumer.Dispose();
            session.Dispose();
            connection.Dispose();
        }
    }
}
